﻿using AutoMapper;
using DTcms.Core.API.Filters;
using DTcms.Core.Common.Emum;
using DTcms.Core.Common.Extensions;
using DTcms.Core.Common.Helper;
using DTcms.Core.IServices;
using DTcms.Core.Model.Models;
using DTcms.Core.Model.ViewModels;
using DTcms.Core.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;


namespace DTcms.Core.API.Controllers
{
    /// <summary>
    /// 友情链接
    /// </summary>
    [Area("api")]
    [Route("api/admin/link")]
    [ApiController]
    public class LinkController : ControllerBase
    {
        private readonly ILinkService _linkService; 
        private readonly IMapper _mapper;
        /// <summary>
        /// 依赖注入
        /// </summary>
        public LinkController(
            ILinkService linkService, IMapper mapper)
        {
            _linkService = linkService;
            _mapper = mapper;
        }
        #region 管理员调用接口==========================

        /// <summary>
        /// 根据ID获取地区
        /// 示例：/api/admin/area/1
        /// </summary>
        [HttpGet("{id}")]
        [Authorize]
        [AuthorizeFilter("Link", ActionType.View)]
        public async Task<IActionResult> GetById([FromRoute] int id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<LinksDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //查询数据库获取实体
            var model = await _linkService.QueryAsync<Links>(x => x.Id == id, WriteRoRead.Write);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"数据[{id}]不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel
            //根据字段进行塑形
            var result = _mapper.Map<LinksDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取站点列表
        /// 示例：/api/admin/link?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet]
        [Authorize]
        [AuthorizeFilter("Link", ActionType.View)]
        public async Task<IActionResult> GetList([FromQuery] BaseParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null && !searchParam.OrderBy.TrimStart('-').IsPropertyExists<LinksDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<LinksDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }

            //获取数据列表
            var list = await _linkService.QueryPageAsync<Links>(
                pageParam.PageSize,
                pageParam.PageIndex,
                   x => !searchParam.Keyword.IsNotNullOrEmpty() || (x.Title != null && x.Title.Contains(searchParam.Keyword)),
                searchParam.OrderBy ?? "SortId,Id");



         

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO
            var resultDto = _mapper.Map<IEnumerable<LinksDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 添加一条记录
        /// 示例：/api/admin/link/
        /// </summary>
        [HttpPost]
        [Authorize]
        [AuthorizeFilter("Link", ActionType.Add)]
        public async Task<IActionResult> Add([FromBody] LinksEditDto modelDto)
        {

           // var result = await _linkService.AddAsync(modelDto);
           //
            var model=_mapper.Map<Links>(modelDto);
            //
            await _linkService.AddAsync(model);

            //
            var result=_mapper.Map<LinksDto>(model);

            return Ok(result);
        }

        /// <summary>
        /// 修改一条记录
        /// 示例：/api/admin/site/1
        /// </summary>
        [HttpPut("{id}")]
        [Authorize]
        [AuthorizeFilter("Link", ActionType.Edit)]
        public async Task<IActionResult> Update([FromRoute] int id, [FromBody] LinksEditDto modelDto)
        {
            var model = await _linkService.QueryAsync<Links>(x => x.Id == id);
            if (model == null) { 
                return NotFound(ResponseMessage.Error($"数据[{id}]不存在或已删除"));
            }
            _mapper.Map(modelDto, model);
            var result = await _linkService.SaveAsync();
            return NoContent();
        }

        /// <summary>
        /// 删除一条记录(级联数据)
        /// 示例：/api/admin/site/1
        /// </summary>
        [HttpDelete("{id}")]
        [Authorize]
        [AuthorizeFilter("Link", ActionType.Delete)]
        public async Task<IActionResult> Delete([FromRoute] int id)
        {
            //取得站点实体信息(带域名)
            var model = await _linkService.QueryAsync<Links>(x => x.Id == id);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"数据[{id}]不存在或已删除"));
            }

            var result = await _linkService.DeleteAsync<Links>(x => x.Id == id);
            return NoContent();
        }

        /// <summary>
        /// 批量删除记录(级联数据)
        /// 示例：/api/admin/site?ids=1,2,3
        /// </summary>
        [HttpDelete]
        [Authorize]
        [AuthorizeFilter("Link", ActionType.Delete)]
        public async Task<IActionResult> DeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //将ID列表转换成IEnumerable
            var arrIds = Ids.ToIEnumerable<int>();
            if (arrIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行删除操作
            var result = await _linkService.DeleteAsync<Links>(x => arrIds.Contains(x.Id));
            return NoContent();
        }


        #endregion

        #region 前台调用接口============================
        /// <summary>
        /// 根据ID或名称获取站点信息
        /// 示例：/api/client/link/1
        /// </summary>
        [HttpGet("/api/client/link/{linkKey}")]
        public async Task<IActionResult> GetClientById([FromRoute] string linkKey, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<LinksDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //查询数据库获取实体
            Links? model = null;
            if (int.TryParse(linkKey, out int linkId))
            {
                model = await _linkService.QueryAsync<Links>(x => x.Id == linkId);
            }
            if (model == null)
            {
                model = await _linkService.QueryAsync<Links>(x => x.Title == linkKey);
            }
            //查询数据库获取实体
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"数据{linkKey}不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel
            //根据字段进行塑形
            var result = _mapper.Map<LinksDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取指定数量列表
        /// 示例：/api/client/link/view/0
        /// </summary>
        [HttpGet("/api/client/link/view/{top}")]
        public async Task<IActionResult> GetClientList([FromRoute] int top, [FromQuery] LinkParameter searchParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<LinksDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<LinksDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }

            //获取数据库列表
            var resultFrom = await _linkService.QueryListAsync<Links>(top,
                x => x.Status == 1
                 && (searchParam.SiteId < 0 || x.SiteId == searchParam.SiteId)
                && (searchParam.IsRecom < 0 || x.IsRecom == searchParam.IsRecom)
                //&& (searchParam.isImage < 0 ? x.LogoUrl == string.Empty : (searchParam.isImage != 1 || x.LogoUrl.length > 1))
                ,
                searchParam.OrderBy ?? "SortId,Id");

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<LinksDto>>(resultFrom).ShapeData(searchParam.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        #endregion
    }
}
